import { useState, useEffect } from 'react';
import { Modal, Input, Button, Tabs, message } from 'antd';
import screenfull from 'screenfull';
import { InbizIcon, getCookie } from '@inbiz/utils';
import Spin from '../Spin';
import { observer } from '@formily/react';
import { TextWidget, getMessage } from '@inbiz/react';
import { approval } from '@components/form/process/ProcessButton/preview/web/service';
import { goto } from '../../../commonUtils';
import { getvars } from '@components/form/process/ProcessButton/preview/commonUtils';
import type { processStructure } from '../../types';
import _ from 'lodash';
import './index.less';

const { TabPane } = Tabs;
export default observer((props: any) => {
  const {
    visible,
    $visible,
    _process,
    getList,
    list,
    $selectedRowKeys,
    pageData,
    condition,
    $choosedItem,
    searchApplyList,
    choosedTabKey,
    applyCatogory,
    $applyList,
    applyList,
    initQuerySelect,
    setLoading,
    $list,
    searchText,
  } = props;

  const [myprocess, $myprocess] = useState(_process);
  const [myProcessLength, $myProcessLength] = useState(0);
  const [opinions, $opinions] = useState('');
  const [progressStep, $progressStep] = useState('1');
  const [loading, $loading] = useState(false);
  const [isFullScreen, $isFullScreen] = useState(false);
  const [canAgree, setCanAgree] = useState(false);
  const [resultData, $resultData] = useState({
    successNumber: 0,
    failureNumber: 0,
    otherNumber: 0,
  });

  const terminate = () => { };
  const remove = (targetKey: string) => {
    const panes = myprocess.filter((pane: { taskId: string }) => pane.taskId !== targetKey);
    $myprocess(panes);
    $myProcessLength(panes.length);
  };
  const onEdit = (targetKey: string) => {
    remove(targetKey);
  };

  const approve = () => {
    $loading(true);
    let newProcess = myprocess?.filter((item1: any) => !item1?.queryData?.url);
    let oldProcess = myprocess?.filter((item1: any) => item1?.queryData?.url);
    let newPromise: any[] = [];
    let oldPromise: any[] = [];
    if (!_.isEmpty(newProcess)) {
      newPromise = newProcess?.map((item: any) => {
        return () => {
          return new Promise(async (resolve, reject) => {
            try {
              let iframeWindow = document.getElementById(item?.taskId)?.contentWindow;
              let variablesParams = iframeWindow?.inbiz?.workFlow?.bpmnVarEntities;
              let params = {
                taskId: item?.taskId,
                comment: opinions,
                signDataStr: '',
                summary: iframeWindow?.inbiz('remark')?.value || '',
                variablesParams: '',
              };
              if (!_.isEmpty(variablesParams)) {
                iframeWindow?.inbiz
                  ?.submit()
                  .then(async (result: any) => {
                    const paramsValue = getvars(result.pageValue, iframeWindow?.inbiz, 'web');
                    params.variablesParams = JSON.stringify(paramsValue);
                    const _result = await approval(params);
                    if (_result?.code == '200') {
                      resolve(true);
                    } else {
                      reject(false);
                    }
                  })
                  .catch((err) => {
                    $loading(false);
                    reject(false);
                  });
              } else {
                iframeWindow?.inbiz?.submit().then(async (result: any) => {
                  if (!result?.id) {
                    reject(false);
                  } else {
                    const _result = await approval(params);
                    if (_result?.code == '200') {
                      resolve(true);
                    } else {
                      reject(false);
                    }
                  }
                });
              }
            } catch (error) {
              reject(false);
            }
          });
        };
      });
    }

    if (!_.isEmpty(oldProcess)) {
      oldPromise = oldProcess?.map((item: any) => {
        return () => {
          return new Promise((resolve, reject) => {
            try {
              let iframeWindow = document.getElementById(item?.taskId)?.contentWindow;
              let textArea = iframeWindow.document
                .getElementsByClassName('edoc2workflowbutton')?.[0]
                .getElementsByTagName('textarea')[0];
              if (textArea) {
                textArea.value = opinions;
              }
              let _buttonsDom = iframeWindow?.document.getElementsByClassName('workflowbuttons');
              for (let i = 0; i < _buttonsDom?.[0]?.childNodes.length; i++) {
                if (_buttonsDom?.[0]?.childNodes[i]?.getAttribute('action') == 'approve') {
                  _buttonsDom?.[0]?.childNodes[i]?.click();
                }
              }
              // let _confirmActions =
              //   iframeWindow?.document.getElementsByClassName('message-confirm-footer')[0];
              // _confirmActions?.childNodes[1]?.click();
              let controlWrapper = iframeWindow?.document.getElementsByClassName(
                'edoc2WorkFlowButtonContainer',
              )[0];
              let controlId = controlWrapper?.getAttribute('controlid');
              iframeWindow
                ?.eform(controlId)
                ?.method('afterSubmit', function (param: { result: boolean }) {
                  if (param.result === true) {
                    resolve(true);
                  } else {
                    reject(false);
                  }
                });
            } catch (error) {
              reject(false);
            }
          });
        };
      });
    }

    let promiseArray = newPromise?.concat(oldPromise);
    let successNumber = 0;
    let failureNumber = 0;

    for (let i = 0; i < promiseArray.length; i++) {
      promiseArray[i]?.()
        .then((res: boolean) => {
          if (res == true) {
            successNumber = successNumber + 1;
          }
        })
        .catch((err: boolean) => {
          if (err == false) {
            failureNumber = failureNumber + 1;
          }
        });
    }

    setTimeout(() => {
      let timer = setInterval(() => {
        if (successNumber + failureNumber == myprocess?.length) {
          $resultData({
            successNumber: successNumber,
            failureNumber: failureNumber,
            otherNumber: 0,
          });
          $loading(false);
          $progressStep('3');
          clearInterval(timer);
        }
      }, 100);
    }, 0);
  };

  const confirmApprove = () => {
    Modal.confirm({
      content: getMessage('processCenter.confirmTosubmitProcess'),
      onOk: approve,
      centered: true,
    });
  };

  const cancel = () => {
    if (progressStep == '3') {
      processCancel();
    } else {
      $visible(false);
      $opinions('');
      sessionStorage.removeItem('batchApproval');
    }
  };

  const processCancel = async () => {
    let _index = 0;
    for (let i = 0; i < list.length; i++) {
      if (list[i]?.taskId == myprocess[myprocess?.length - 1]?.taskId) {
        _index = i;
      }
    }
    const newList = list?.map((item: any) => ({
      ...item,
      checked: false,
    }));
    $list(newList);
    $visible(false);
    let curCatogoryCount = applyCatogory?.filter(
      (item: any) => item?.name == condition?.pGroupName,
    )?.[0]?.count;
    let curApplyCount = applyList?.filter((item: any) => item?.id == condition?.pDefId)?.[0]?.count;
    setLoading(true);
    if (curCatogoryCount == 1 || curApplyCount == 1) {
      await initQuerySelect();
    }
    await getList(
      list?.length == resultData?.successNumber && pageData.pageIndex != 1
        ? pageData.pageIndex - 1
        : pageData.pageIndex,
      pageData.pageSize,
      '2',
      searchText,
      curCatogoryCount == 1 || curApplyCount == 1
        ? {
          processGroupName: '',
          processDefId: '',
          date: '',
          status: '',
        }
        : condition,
      () => {
        if (curCatogoryCount == 1 || curApplyCount == 1) {
          searchApplyList(choosedTabKey, () => {
            const arr = applyCatogory.find((ele) => ele.id == condition?.pGroupName).children;
            $applyList([
              { id: '', name: 'processCenter.all', proLcon: 'font_family' },
              ...arr,
            ]);
          });
        }
        if (choosedTabKey == '2' && list?.length >= 10) {
          setTimeout(() => {
            let _wrapper = document.getElementsByClassName('cardInfo')[0];
            if (_wrapper) {
              let _scrollBody = _wrapper.getElementsByClassName('cardInfoContainer')[0];
              let _item =
                _scrollBody.getElementsByClassName('cardItem')[
                list?.length > (_index || 0) ? _index : list?.length
                ];
              _item.scrollIntoView();
            } else {
              let __wrapper = document.getElementsByClassName('inbiz-processCenter-table')[0];
              if (__wrapper) {
                let __scrollBody = __wrapper.getElementsByClassName('ant-table-tbody')[0];
                let __item =
                  __scrollBody.getElementsByTagName('tr')[
                  list?.length > (_index || 0) ? _index : list?.length
                  ];
                __item.scrollIntoView();
              }
            }
          }, 0);
        }
      },
    );
    $choosedItem([]);
    $selectedRowKeys([]);
    $opinions('');
    if (!(curCatogoryCount == 1 || curApplyCount == 1)) {
      searchApplyList(choosedTabKey, () => {
        let arr = applyCatogory.find((ele) => ele.id == condition?.pGroupName)?.children;
        $applyList([
          { id: '', name: 'processCenter.all', proLcon: 'font_family' },
          ...arr,
        ]);
      });
      if (condition.pGroupName) {
        let arr = applyCatogory.find((ele) => ele.id == condition.pGroupName)?.children || [];
        $applyList([
          { id: '', name: 'processCenter.all', proLcon: 'font_family' },
          ...arr,
        ]);
      } else {
        let arr = applyCatogory.find((ele) => ele.id == condition.pGroupName)?.children || [];
        $applyList([
          { id: '', name: 'processCenter.all', proLcon: 'font_family' },
          ...arr,
        ]);
      }
    }
    sessionStorage.removeItem('batchApproval');
    setLoading(false);
  };

  const getReadyForApproval = () => {
    setCanAgree(false);
    let newProcess = myprocess?.filter((item: any) => !item?.queryData?.url);
    let oldProcess = myprocess?.filter((item: any) => item?.queryData?.url);
    let newPromise: any[] = [];
    let oldPromise: any[] = [];
    if (!_.isEmpty(newProcess)) {
      newPromise = newProcess?.map((item: any) => {
        return () => {
          return new Promise((resolve, reject) => {
            let timer = setInterval(() => {
              let iframeWindow = document.getElementById(item?.taskId)?.contentWindow;
              if (iframeWindow?.inbiz) {
                resolve(true);
                clearInterval(timer);
              }
            }, 100);
          });
        };
      });
    }

    if (!_.isEmpty(oldProcess)) {
      oldPromise = oldProcess?.map((item: any) => {
        return () => {
          return new Promise((resolve, reject) => {
            let timer = setInterval(() => {
              let iframeWindow = document.getElementById(item?.taskId)?.contentWindow;
              if (iframeWindow?.eform?.formEngine?.isLoaded) {
                resolve(true);
                clearInterval(timer);
              }
            }, 100);
          });
        };
      });
    }

    let promiseArray = newPromise?.concat(oldPromise);
    let successNumber = 0;
    let failureNumber = 0;

    for (let i = 0; i < promiseArray.length; i++) {
      promiseArray[i]?.()
        .then((res: boolean) => {
          if (res == true) {
            successNumber = successNumber + 1;
          }
        })
        .catch((err: boolean) => {
          if (err == false) {
            failureNumber = failureNumber + 1;
          }
        });
    }

    setTimeout(() => {
      let timer1 = setInterval(() => {
        if (myprocess?.length == successNumber + failureNumber) {
          setCanAgree(true);
          clearInterval(timer1);
        }
      }, 100);
    }, 0);
  }

  const footerButton =
    progressStep == '1' ? (
      <>
        <Button type="primary" onClick={confirmApprove} disabled={!canAgree}>
          <TextWidget>processCenter.agree</TextWidget>
        </Button>
        <Button onClick={cancel}>
          <TextWidget>global.cancel</TextWidget>
        </Button>
      </>
    ) : (
      <Button type="primary" onClick={progressStep == '2' ? terminate : processCancel}>
        {progressStep == '2'
          ? getMessage('processCenter.forceTerminate')
          : getMessage('global.sure')}
      </Button>
    );

  const getFullScreenElement = () => {
    let managerModal = document.getElementsByClassName(
      'batchModal',
    )[0];
    let fullScreenElement =
      managerModal?.getElementsByClassName('ant-modal-content')[0];
    return fullScreenElement;
  };
  const changeModal = (e) => {
    e.stopPropagation();
    screenfull.toggle(getFullScreenElement());
    $isFullScreen(!isFullScreen);
  };

  useEffect(() => {
    $myprocess(_process);
    $myProcessLength(_process.length);
  }, [_process]);

  useEffect(() => {
    if (visible && myprocess?.length) {
      $progressStep('1');
      getReadyForApproval();
    }
  }, [myprocess, visible]);

  const onTabsChange = (id: string) => {
    let curIframe = document.getElementById(id);
    curIframe?.contentWindow?.location?.reload();
    getReadyForApproval();
  };

  return (
    <Modal
      title={getMessage('processCenter.batchApproval')}
      footer={footerButton}
      destroyOnClose
      visible={visible}
      onCancel={cancel}
      width={progressStep == '3' ? 600 : 1003}
      className={`batchModal`}
      bodyStyle={{
        maxHeight: document.body.clientHeight - 138,
        overflow: 'auto',
        padding: '0px 20px 0',
      }}
      closeIcon={
        <div>
          <InbizIcon
            onClick={(e) => changeModal(e)}
            type={isFullScreen ? 'icon-huanyuan' : 'icon-ic-zuidahua'}
            style={{ fontSize: 22, marginRight: 20 }}
          />
          <InbizIcon type="icon-ic-close-bold" style={{ fontSize: 22 }} />
        </div>
      }
    >
      <Spin spinning={loading}>
        {progressStep == '1' && (
          <div style={{ width: '100%', height: '100%' }}>
            <Tabs type="editable-card" onEdit={onEdit} hideAdd onChange={onTabsChange}>
              {myprocess?.map((item: processStructure, index: number) => {
                let _url = !item?.queryData?.url
                  ? `${location.origin}${process.env.NODE_ENV == 'development' ? '' : '/inbiz/web'}/${item?.queryData?.siteDomName
                  }?dataVersionId=${item?.queryData?.pageVersion || ''}#${process.env.NODE_ENV == 'development' ? '/preview/page' : '/page'
                  }${item?.queryData?.routeId}?id=${item?.queryData?.id}&taskId=${item?.queryData?.taskId
                  }&processId=${item?.queryData?.processId}&instanceId=${item?.queryData?.instanceId
                  }&formId=${item?.queryData?.formId}&tabKey=2&drafID=&taskState=0&pageId=${item?.queryData?.pageId
                  }`
                  : `${item?.queryData?.url}?formId=${item?.queryData?.formId
                  }&skin=lighttechblue&processId=${item?.queryData?.processId
                  }&taskType=inboxtask&taskId=${item?.queryData?.taskId}&id=${item?.queryData?.businessKey
                  }&incidentId=${item?.queryData?.processInstanceId}&token=${getCookie(
                    'token',
                  )}&isArchiveTask=false&taskState=0&formver=${item?.queryData?.formver
                  }&ishide=true&islog=true&isPop=true`;
                return (
                  <TabPane
                    key={item.taskId}
                    tab={`${item.processInstanceId}-${item.initiatorName}`}
                    forceRender={true}
                  >
                    <header>
                      <TextWidget>processCenter.applycontent</TextWidget>{' '}
                      <InbizIcon
                        type="icon-process-liuchengrizhi-feiji"
                        onClick={(e) => {
                          goto(
                            {
                              taskIds: item.taskId,
                              processInstanceId: item.processInstanceId,
                              inItiateApplication: false,
                              taskState: item.taskState,
                              siteType: 0,
                            },
                            '2',
                            'web',
                            e,
                          );
                        }}
                      />
                    </header>
                    <iframe
                      id={item.taskId}
                      style={{
                        height: '437px',
                        width: '955px',
                        border: '1px solid #d0d4d9',
                        marginTop: '10px',
                        overflow: 'auto',
                        borderRadius: 8,
                      }}
                      src={_url}
                    />
                  </TabPane>
                );
              })}
            </Tabs>
            <section style={{ paddingBottom: 1 }}>
              <Input.TextArea
                placeholder={getMessage('processCenter.comment')}
                value={opinions}
                onChange={(e) => {
                  const _value = e.target.value;
                  if (_value && _value?.length > 163) {
                    message.error(getMessage('processCenter.tooManyComment'));
                    return;
                  }
                  $opinions(_value)
                }}
                autoSize={{ minRows: 4, maxRows: 4 }}
                allowClear
                style={{ width: 400, marginTop: 20 }}
              />
            </section>
          </div>
        )}
        {progressStep == '3' && (
          <section className="thirdStep">
            <h2>
              <TextWidget>processCenter.batchapprovalComplete</TextWidget>
            </h2>

            <div style={{ color: '#707070', marginTop: 15, marginBottom: 25 }}>{`${getMessage(
              'processCenter.common',
            )}${myProcessLength}${getMessage('processCenter.processes')}`}</div>
            <h3>
              <div>
                <InbizIcon type="icon-yiwancheng" style={{ fontSize: 28, marginRight: 15 }} />
              </div>
              <div>
                <TextWidget>processCenter.approvalSuccess</TextWidget>: {resultData.successNumber}
                <TextWidget>processCenter.unit</TextWidget>
              </div>
            </h3>
            <h3>
              <div>
                <InbizIcon
                  type="icon-ic-jiancecuowu"
                  style={{ color: '#EC705F', fontSize: 28, marginRight: 15 }}
                />
              </div>
              <div>
                <TextWidget>processCenter.approvalFail</TextWidget>: {resultData.failureNumber}
                <TextWidget>processCenter.unit</TextWidget>
              </div>
            </h3>
            {resultData.otherNumber !== 0 && (
              <h3>
                <div>
                  <InbizIcon
                    type="icon-jinggao"
                    style={{ color: '#afafaf', fontSize: 28, marginRight: 15 }}
                  />
                </div>
                <div>
                  <TextWidget>processCenter.notApproval</TextWidget>: {resultData.otherNumber}
                  <TextWidget>processCenter.unit</TextWidget>
                </div>
              </h3>
            )}
          </section>
        )}
      </Spin>
    </Modal>
  );
});
